/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.easyedu.dictionary.gui.actions;

import eu.easyedu.dictionary.api.model.Dictionary;
import eu.easyedu.dictionary.api.util.DatabaseUtils;
import eu.easyedu.dictionary.api.util.DictionaryManager;
import eu.easyedu.dictionary.gui.MainDictionaryTopComponent;
import eu.easyedu.dictionary.gui.resources.Bundle;
import java.awt.event.ActionEvent;
import java.util.Collection;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.SwingUtilities;
import org.openide.util.ContextAwareAction;
import org.openide.util.Lookup;
import org.openide.util.Lookup.Item;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.Utilities;
import org.openide.windows.TopComponent;

/**
 *
 * @author hlavki
 */
public class DeleteDictionaryAction extends AbstractAction implements LookupListener, ContextAwareAction {

    private static final long serialVersionUID = 1L;
    private Lookup context;
    private Lookup.Result<Dictionary> lookupResult;

    public DeleteDictionaryAction() {
        this(Utilities.actionsGlobalContext());
    }

    private DeleteDictionaryAction(Lookup context) {
        super(Bundle.getMessage("DeleteDictionaryAction.text"));
        this.context = context;
    }

    void init() {
        assert SwingUtilities.isEventDispatchThread() : "this shall be called just from AWT thread";
        if (lookupResult != null) {
            return;
        }
        Lookup.Template<Dictionary> tpl = new Lookup.Template<Dictionary>(Dictionary.class);
        lookupResult = context.lookup(tpl);
        lookupResult.addLookupListener(this);
        resultChanged(null);
    }

    public void actionPerformed(ActionEvent e) {
        init();
        Collection<? extends Item<Dictionary>> items = lookupResult.allItems();
        for (Item<Dictionary> item : items) {
            Dictionary dict = item.getInstance();
            TopComponent win = MainDictionaryTopComponent.findInstance(dict);
            win.close();
            DictionaryManager.getDefault().removeDictionary(dict);
        }
    }

    public Action createContextAwareInstance(Lookup actionContext) {
        return new DeleteDictionaryAction(actionContext);
    }

    public void resultChanged(LookupEvent ev) {

    }
}
